from django.db import models
from utils.models import Basemodel
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from mall import settings


class OAuthQQUser(Basemodel):
    user = models.ForeignKey('users.User', on_delete=models.CASCADE, verbose_name='用户')
    openid = models.CharField(max_length=64, verbose_name='openid', db_index=True)

    class Meta:
        # 设置元类
        db_table = 'tb_oauth_qq'
        verbose_name = 'QQ登录用户数据'
        verbose_name_plural = verbose_name
    @staticmethod
    def generate_save_user_token(openid):
        # 生成jwttoken保护用户信息
        ## 获取秘钥
        serializer = Serializer(settings.SECRET_KEY, expires_in=3600)
        ## 加密openid
        token = serializer.dumps({'openid': openid})

        return token.decode()

    @staticmethod
    def check_save_user_token(token):
        # 获取itdang的秘钥
        serializer = Serializer(settings.SECRET_KEY,3600)
        try:
            # 解密获取明文
            result = serializer.loads(token)
        except BadData:
            # 解密失败返回空
            return None
        # 最终返回openid的明文
        return result.get('openid')



